import { QuestionType } from '@/components/question/typing';
import useQuestionnaireStore from '@/store/questionnaire';
import { message } from 'ant-design-vue';
import { defineComponent, ref } from 'vue';
import { RouterView } from 'vue-router';
import { createQuestionDesignData } from '../question/utils';
import QuestionAttributePanel from './question-attribute-panel';
import QuestionTypespanel from './question-types-panel';
import './style.css';
export default defineComponent({
  setup() {
    const questionnaireStore = useQuestionnaireStore();
    const basicInfo = questionnaireStore.getBasicInfo;
    const questions = questionnaireStore.getQuestions;
    const activeQuestion = ref();

    const questionTypeDblClick = (questionType: QuestionType) => {
      if (questionType.type === 'startPage') {
        const startPageQuestion = questions?.find(
          eachQuestion => eachQuestion.type === 'startPage',
        );
        if (startPageQuestion !== undefined) {
          message.warn('只能添加一个开始页面！', 3);
          console.error('只能添加一个开始页面！');

          return;
        }
      }
      const newQuestionIndex = questions?.length ? questions.length : 0;
      const _basicInfo = questionnaireStore.getBasicInfo;
      const newData = createQuestionDesignData(
        questionType.type,
        _basicInfo.language,
        newQuestionIndex,
      );
      _basicInfo.activeQuestionIndex = newQuestionIndex;
      questionnaireStore.setBasicInfo(_basicInfo);
      questions?.push(newData);
      activeQuestion.value = newData;
    };

    const questionClick = (question: QuestionType, _index: number) => {
      activeQuestion.value = question;
    };

    if (questions && questions.length && questions.length > 0) {
      basicInfo.activeQuestionIndex = 0;
      activeQuestion.value = questions[0];
      questionnaireStore.setBasicInfo(basicInfo);
    }

    return () => {
      return (
        <div class="design-container">
          <QuestionTypespanel onQuestionDblClick={questionTypeDblClick} />
          <RouterView
            {...{
              questions: questions,
              onQuestionClick: questionClick,
            }}
          />
          {activeQuestion.value ? (
            <QuestionAttributePanel
              key={`question-attribute-panel-${activeQuestion.value.id}`}
              question={activeQuestion.value}
              language={basicInfo.language}
            />
          ) : (
            <></>
          )}
        </div>
      );
    };
  },
});
